//
//  OrdersTableViewCell.m
//  GoBigMarket
//
//  Created by 李真 on 16/8/22.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "OrdersTableViewCell.h"
#import "OrdersCellModel.h"
#import "Order.h"
#import "BeeCloud.h"
#import <AlipaySDK/AlipaySDK.h>
@interface OrdersTableViewCell()

@end

@implementation OrdersTableViewCell

//支付
- (IBAction)lastBtn:(id)sender {
//    [self goCount];
    [self pullAlert];

}
#pragma mark - 选择支付方式
- (void)pullAlert {
    UIAlertController *sheetController = [UIAlertController alertControllerWithTitle:@"请选择支付方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"支付宝支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self goCount];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"微信支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self beeCloudPayOrder];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        DLog(@"取消");
    }];
#warning Cancel按钮一直在最下边，并且上拉菜单类型不可以添加文本框
    [sheetController addAction:action1];
    [sheetController addAction:action2];
    [sheetController addAction:action3];
    [self.viewController presentViewController:sheetController animated:YES completion:^{
        
    }];
}
#pragma mark - beeCloud 微信去支付
- (void)beeCloudPayOrder {
    [CQNetWorkTools POSTWithURL:beeCloudSubmitOrder par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"OrderId":self.model.Id,@"PlatType": @"IOS"} success:^(id responseObject) {
        
        NSString *BillNum =[responseObject objectForKey:@"BillNum"];
        NSString *BillTitle =[responseObject objectForKey:@"BillTitle"];
        NSString *BillTotalFee =[responseObject objectForKey:@"BillTotalFee"];
        NSString *PayId = [responseObject objectForKey:@"PayId"];
        [self doPay:PayChannelWxApp BillNum:BillNum BillTitle:BillTitle BillTotalFee:BillTotalFee PayId:PayId];
    } filed:^(NSError *error) {
        
    }];
}
#pragma mark - beeCloud支付
- (void)doPay:(PayChannel)channel BillNum:(NSString *)BillNum BillTitle:(NSString *)BillTitle BillTotalFee:(NSString *)BillTotalFee PayId:(NSString *)PayId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value",@"key", nil];
    /**
     按住键盘上的option键，点击参数名称，可以查看参数说明
     **/
    BCPayReq *payReq = [[BCPayReq alloc] init];
    /**
     *  支付渠道，PayChannelWxApp,PayChannelAliApp,PayChannelUnApp,PayChannelBaiduApp
     */
    payReq.channel = channel; //支付渠道
    payReq.title = BillTitle;//订单标题
    payReq.totalFee = [NSString stringWithFormat:@"%@", BillTotalFee];//订单价格; channel为BC_APP的时候最小值为100，即1元
    payReq.billNo = [NSString stringWithFormat:@"%@", BillNum];//商户自定义订单号
    
    payReq.scheme = @"wxdeaf20c134765733";//URL Scheme,在Info.plist中配置; 支付宝必有参数
    payReq.billTimeOut = 300;//订单超时时间
    payReq.viewController = self.viewController; //银联支付和Sandbox环境必填
    payReq.cardType = 0; //0 表示不区分卡类型；1 表示只支持借记卡；2 表示支持信用卡；默认为0
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}

#pragma mark - 去结算方法
- (void)goCount {
    self.encodeStr = [NSMutableString string];
    //    NSLog(@"去结算啊啊%@--%@--%@--%@",GETPHONE,GETTOKEN,GETUUID,self.orderStr);
    
    [CQNetWorkTools POSTWithURL:ShopCartGoPay par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"OrderId":self.model.Id,@"PlatType": @"IOS"} success:^(id responseObject) {
        DLog(@"去结算成功%@", [responseObject objectForKey:@"Parm"]);
        NSString *parm = [responseObject objectForKey:@"Parm"];
        NSArray *array = [parm componentsSeparatedByString:@"&"];
        DLog(@"%@", array);
        Order* order = [Order new];
        // NOTE: 商品数据
        order.biz_content = [BizContent new];
        for (int i =0 ; i < array.count; i++) {
            NSString *str = [array objectAtIndex:i];
            NSArray *arr = [str componentsSeparatedByString:@"="];
            NSString *string = [NSString string];
            if (arr.count == 3) {
                string = [[arr objectAtIndex:1]  stringByAppendingString:@"="];
            }else {
                string = [arr lastObject];
            }
            NSString *key = [arr firstObject];
            switch (i) {
                case 0:{
                    // NOTE: app_id设置
                    order.app_id = string;
                    DLog(@"软件号码%@", self.encodeStr);
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.app_id]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 1:{
                    DLog(@"方法%@", self.encodeStr);
                    // NOTE: 支付接口名称
                    order.method = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.method]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 2:{
                    DLog(@"方式%@", self.encodeStr);
                    order.charset = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.charset]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 3:{
                    DLog(@"加签格式%@", self.encodeStr);
                    // NOTE: 参数编码格式
                    order.sign_type = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.sign_type]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 4:{
                    DLog(@"时间%@", self.encodeStr);
                    // NOTE: 当前时间点
                    order.timestamp = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.timestamp]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 5:{
                    // NOTE: 支付版本
                    order.version = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.version]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 6:
                {
                    order.notify_url = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.notify_url]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 7:{
                    // NOTE: sign_type设置
                    order.biz = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.biz]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 8:{
                    order.sign = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.sign]stringByAppendingString:@"="].mutableCopy;
                }
                    break;
                default:
                    break;
            }
        }
        DLog(@"最后字符串%@", self.encodeStr);
        NSString *appScheme = @"GoBigMarket";
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:self.encodeStr
                                  fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            DLog(@"reslut = %@",resultDic);
            if ([[responseObject valueForKey:@"resultStatus"]integerValue] == 9000) {
                //发通知刷新订单列表
                [[NSNotificationCenter defaultCenter]postNotificationName:@"QuXiaoDingDan" object:nil];
            }
        }];
    } filed:^(NSError *error) {
        DLog(@"去结算失败%@", error);
    }];
}

//取消订单
- (IBAction)firstBtn:(id)sender {
    [self createAlertControllerWithMessage:@"确定要取消订单吗？"];
}
#pragma mark - 确认收货
- (IBAction)enterBtn:(id)sender {
    DLog(@"确认收货");
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.lastBtn.layer.masksToBounds = YES;
    self.lastBtn.layer.cornerRadius = 5;
//    self.enterBtn.layer.masksToBounds = YES;
//    self.enterBtn.layer.cornerRadius = 5;
    self.img1.layer.masksToBounds = self.img2.layer.masksToBounds = YES;
    self.img1.layer.cornerRadius = self.img2.layer.cornerRadius = 42;
//    self.img1.layer.borderWidth = self.img2.layer.borderWidth = 1;
//    self.img1.layer.borderColor = self.img2.layer.borderColor = [[UIColor lightGrayColor] CGColor];
}

-(void)setPicArr:(NSArray *)picArr{
    if (_picArr != picArr) {
        _picArr = picArr;
    }
    [self.img1 sd_setImageWithURL:[NSURL URLWithString:picArr[0]]];
    if (picArr.count == 2) {
    [self.img2 sd_setImageWithURL:[NSURL URLWithString:picArr[1]]];
    }
}
-(void)setModel:(OrdersModel *)model{
    if (_model != model) {
        _model = model;
    }
    /**
     *  订单状态，1待付款,2待发货,3待收货,4已关闭,5已完成,7未评价。这里返回数字用于判断订单环节状态
     */
//    self.statesLabel.text = model.OrderStatus;
    
    switch ([model.OrderStatus integerValue]) {
        case 1:
            self.statesLabel.text = @"待付款";
            self.lastBtn.hidden = NO;
            self.firstBtn.hidden = NO;
            break;
        case 2:
            self.statesLabel.text = @"待发货";
            break;
        case 3:
            self.statesLabel.text = @"待收货";
//            self.enterBtn.hidden = NO;
            break;
        case 4:
            self.statesLabel.text = @"已关闭";
            break;
        case 5:
            self.statesLabel.text = @"已完成";
            break;
        case 7:
            self.statesLabel.text = @"未评价";
            break;
        default:
            break;
    }
    
    self.shangpinLabel.attributedText = [self strRed2AndSizeWithStr:[NSString stringWithFormat:@"共%d类商品",model.Count4Products]];

    self.allLabel.attributedText = [self strRedAndSizeWithStr:[NSString stringWithFormat:@"%.2f元",model.OrderTotalAmount]];
    self.timeLabel.text = [NSString stringWithFormat:@"下单时间:%@", model.OrderDate];

    self.nameLbale.attributedText = [self strSuoJinWithStr:[NSString stringWithFormat:@"%@", model.ShopName]];
    NSMutableArray *arr= [NSMutableArray array];
    
    for (NSDictionary *dic in model.Products) {
        
        [arr addObject:[NSString stringWithFormat:@"%@%@",ReleaseORDebug,[dic valueForKey:@"ThumbnailsUrl"]]];
    }
    self.picArr = arr;
}



//字体变色
- (NSAttributedString *)strRedAndSizeWithStr:(NSString *)str{
  
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedString addAttribute:NSForegroundColorAttributeName value:GDJColor(236, 152, 18) range:NSMakeRange(0, str.length - 1)];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:23] range:NSMakeRange(0, str.length - 1)];
    
    return attributedString;
}
- (NSAttributedString *)strRed2AndSizeWithStr:(NSString *)str{
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedString addAttribute:NSForegroundColorAttributeName value:GDJColor(236, 152, 18) range:NSMakeRange(1,1)];
   
    return attributedString;
}
//行缩进
- (NSAttributedString *)strSuoJinWithStr:(NSString *)str{
    //售价
    
    NSMutableParagraphStyle *paraStyle01 = [[NSMutableParagraphStyle alloc] init];
    paraStyle01.alignment = NSTextAlignmentLeft;  //对齐
    paraStyle01.headIndent = 0.0f;//行首缩进
    //参数：（字体大小17号字乘以2，34f即首行空出两个字符）
    CGFloat emptylen = 5.0f;
    paraStyle01.firstLineHeadIndent = emptylen;//首行缩进
//    paraStyle01.tailIndent = 10.0f;//行尾缩进
//    paraStyle01.lineSpacing = 2.0f;//行间距
    
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:str attributes:@{NSParagraphStyleAttributeName:paraStyle01}];
    
    return attrText;
}
#pragma mark - 弹窗设置

- (void)createAlertControllerWithMessage:(NSString *)message {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *centerAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    
        NSDictionary *par = @{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"OrderId":self.model.Id};
        [CQNetWorkTools POSTWithURL:PostQuXiaoOreder par:par success:^(id responseObject) {
            DLog(@"取消订单 %@",responseObject);
            [[NSNotificationCenter defaultCenter]postNotificationName:@"QuXiaoDingDan" object:nil];
        } filed:^(NSError *error) {
            DLog(@"取消订单 错误 %@",error);
        }];
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:centerAction];
    [alertController addAction:cancelAction];
    [self.viewController presentViewController:alertController animated:YES completion:^{
        
    }];
}
@end
